package Z6;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.script.*;
import javax.swing.JOptionPane;

import sun.org.mozilla.javascript.internal.*;

/*
 Zadanie 1 (max 1 punkt)
 - w swojej tresci bedzie mial skrypt JavaScript (np. przechowywany w zmiennej typu String)
 - skrypt ten bedzie mial za zadanie otworzenie input dialogu i wczytanie lancucha od uzytkownika
 - to co uzytkownik wpisze bedzie lancuchem tekstowym oznaczajacym nazwe metody oraz 
 liczbe jako jej argument (np. â€śwyswietl 5â€ť - â€�wyswietlâ€™ to nazwa metody, a â€�5â€™ to jej 
 argument
 */

public class Zadanie {
	public static void main(String[] args) throws NoSuchMethodException,
			ScriptException {
		ScriptEngineManager manager = new ScriptEngineManager();

		// Zadanie 1
		ScriptEngine engine = manager.getEngineByName("rhino");
		//Bindings bindings = engine.createBindings();
		String script = engine
				.getFactory()
				.getProgram("importPackage (javax.swing)",
						"s=JOptionPane.showInputDialog('Podaj nazwe metody i argument')",
						"wywolajMetodeZJS('s')");
		engine.eval(script);
		//NativeJavaObject o = (NativeJavaObject) bindings.get("s");
		//String str = o.unwrap().toString();
		//Object ob=wywolajMetodeZJS(bindings.get("s").toString());
		/*String str=((NativeJavaObject) bindings.get("s")).unwrap().toString();
		
		// Zadanie 2
		ScriptEngine engine2 = manager.getEngineByName("rhino");
		String script2 = "importPackage (javax.swing);function square(n) {return n*n;};function wyswietl(n){JOptionPane.showMessageDialog(null, ''+n);return n;}";
		// engine2.eval(new FileReader("skrypt2.js"));
		engine2.eval(script2);
		String[] str_tab = str.split(" ");
		Invocable eng = (Invocable) engine2;
		Object ob = eng.invokeFunction(str_tab[0], str_tab[1]);*/
		//System.out.println(ob);

	}
	
	static void wywolajMetodeZJS(String s) throws NoSuchMethodException, ScriptException{
		System.out.println(s);
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine2 = manager.getEngineByName("rhino");
		String script2 = "importPackage (javax.swing);function square(n) {return n*n;};function wyswietl(n){JOptionPane.showMessageDialog(null, ''+n);return n;}";
		// engine2.eval(new FileReader("skrypt2.js"));
		engine2.eval(script2);
		String[] str_tab = s.split(" ");
		Invocable eng = (Invocable) engine2;
		Object ob = eng.invokeFunction(str_tab[0], str_tab[1]);
		System.out.println(ob);
	}
}
